<template>
  <view class="content">
    <!-- 顶部导航 -->
    <page-header
      title="全部标签"
      :showBack="true"
      :customBack="handleBack"
      @back="handleBack"
    >
      <!-- 右侧添加按钮 -->
      <template #right>
        <view class="header-icon" @click="showAddDialog">
          <image class="icon-svg" src="/static/svgs/add.svg"></image>
        </view>
      </template>
    </page-header>

    <!-- 主体内容 -->
    <view class="page-body">
      <!-- 标签列表 -->
      <view class="label-list">
        <view
          v-for="label in labels"
          :key="label.id"
          class="label-item"
          :class="{ hidden: label.hidden }"
        >
          <view class="label-info">
            <text class="label-name">{{ label.name }}</text>
            <text class="label-status" v-if="label.hidden">已隐藏</text>
          </view>
          <view class="label-actions">
            <view class="action-btn edit" @click="editLabel(label)">
              <image class="action-icon" src="/static/svgs/edit.svg"></image>
            </view>
            <view
              class="action-btn toggle"
              @click="toggleLabelVisibility(label)"
            >
              <image
                class="action-icon"
                :src="
                  label.hidden
                    ? '/static/svgs/eye-off.svg'
                    : '/static/svgs/eye.svg'
                "
              ></image>
            </view>
            <view class="action-btn delete" @click="deleteLabel(label)">
              <image class="action-icon" src="/static/svgs/delete.svg"></image>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-if="labels.length === 0" class="empty-state">
        <image class="empty-icon" src="/static/svgs/tag-none.svg"></image>
        <text class="empty-text">暂无标签</text>
        <text class="empty-tip">点击右上角添加标签</text>
      </view>
    </view>

    <!-- 添加/编辑标签弹窗 -->
    <view v-if="showDialog" class="dialog-mask" @click="hideDialog">
      <view class="dialog-content" @click.stop>
        <view class="dialog-header">
          <text class="dialog-title">{{
            isEditing ? "编辑标签" : "添加标签"
          }}</text>
        </view>
        <view class="dialog-body">
          <input
            class="label-input"
            v-model="labelName"
            placeholder="请输入标签名称"
            maxlength="20"
            @confirm="confirmAction"
          />
        </view>
        <view class="dialog-footer">
          <button class="dialog-btn cancel" @click="hideDialog">取消</button>
          <button class="dialog-btn confirm" @click="confirmAction">
            确定
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import pageHeader from "@/components/pageHeader.vue";
import { tagApi } from "@/api";

// 页面数据
const labels = ref([]);
const showDialog = ref(false);
const isEditing = ref(false);
const labelName = ref("");
const editingLabel = ref(null);

// 页面方法
const handleBack = () => {
  // 通知首页重新获取标签数据
  uni.$emit("refreshLabels");
  uni.navigateBack();
};

const showAddDialog = () => {
  isEditing.value = false;
  labelName.value = "";
  editingLabel.value = null;
  showDialog.value = true;
};

const editLabel = (label) => {
  isEditing.value = true;
  labelName.value = label.name;
  editingLabel.value = label;
  showDialog.value = true;
};

const hideDialog = () => {
  showDialog.value = false;
  labelName.value = "";
  editingLabel.value = null;
};

const confirmAction = async () => {
  if (!labelName.value.trim()) {
    uni.showToast({
      title: "请输入标签名称",
      icon: "none",
    });
    return;
  }

  try {
    uni.showLoading({
      title: isEditing.value ? "更新中..." : "添加中...",
    });

    if (isEditing.value) {
      // 编辑标签逻辑
      const result = await tagApi.updateLabel({
        id: editingLabel.value.id,
        name: labelName.value.trim(),
      });

      if (result.success) {
        // 更新本地数据
        const index = labels.value.findIndex(
          (item) => item.id === editingLabel.value.id
        );
        if (index !== -1) {
          labels.value[index].name = labelName.value.trim();
        }

        uni.showToast({
          title: "更新成功",
          icon: "success",
        });
      } else {
        uni.showToast({
          title: result.msg || "更新失败",
          icon: "error",
        });
      }
    } else {
      // 添加标签逻辑
      const result = await tagApi.addLabel({
        name: labelName.value.trim(),
      });

      if (result.success) {
        // 重新获取标签列表
        await loadLabels();
      } else {
        uni.showToast({
          title: result.msg || "添加失败",
          icon: "error",
        });
      }
    }

    hideDialog();
  } catch (error) {
    console.error("操作失败:", error);
    uni.showToast({
      title: "操作失败，请稍后重试",
      icon: "error",
    });
  } finally {
    uni.hideLoading();
  }
};

const toggleLabelVisibility = async (label) => {
  try {
    uni.showLoading({
      title: label.hidden ? "显示中..." : "隐藏中...",
    });

    let result;

    if (label.hidden) {
      // 展示标签
      result = await tagApi.showLabel({ id: label.id });
    } else {
      // 隐藏标签 - 需要传递当前展示的所有标签id数组（排除要隐藏的标签）
      const visibleLabelIds = labels.value
        .filter((item) => !item.hidden && item.id !== label.id)
        .map((item) => item.id);
      result = await tagApi.hideLabel(visibleLabelIds);
    }

    if (result.success) {
      // 重新获取标签列表以确保数据一致性
      await loadLabels();

      uni.showToast({
        title: label.hidden ? "已显示" : "已隐藏",
        icon: "success",
      });
    } else {
      uni.showToast({
        title: result.msg || "操作失败",
        icon: "error",
      });
    }
  } catch (error) {
    console.error("切换显示状态失败:", error);
    uni.showToast({
      title: "操作失败，请稍后重试",
      icon: "error",
    });
  } finally {
    uni.hideLoading();
  }
};

const deleteLabel = (label) => {
  uni.showModal({
    title: "删除标签",
    content: `确定要删除标签"${label.name}"吗？`,
    confirmColor: "#FF3B30",
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({
            title: "删除中...",
          });

          const result = await tagApi.deleteLabel({ id: label.id });

          if (result.success) {
            // 从本地数据中移除
            const index = labels.value.findIndex(
              (item) => item.id === label.id
            );
            if (index !== -1) {
              labels.value.splice(index, 1);
            }

            uni.showToast({
              title: "删除成功",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: result.msg || "删除失败",
              icon: "error",
            });
          }
        } catch (error) {
          console.error("删除标签失败:", error);
          uni.showToast({
            title: "删除失败，请稍后重试",
            icon: "error",
          });
        } finally {
          uni.hideLoading();
        }
      }
    },
  });
};

const loadLabels = async () => {
  try {
    uni.showLoading({
      title: "加载中...",
    });

    // 并行获取全部标签和展示标签
    const [allLabelsResult, shownLabelsResult] = await Promise.all([
      tagApi.getLabelList(),
      tagApi.getLabelListShow(),
    ]);

    if (allLabelsResult.success && allLabelsResult.data) {
      // 获取展示标签的id集合
      const shownLabelIds = new Set();
      if (shownLabelsResult.success && shownLabelsResult.data) {
        shownLabelsResult.data.forEach((item) => {
          shownLabelIds.add(item.id);
        });
      }

      // 设置标签的hidden状态
      labels.value = allLabelsResult.data.map((item) => ({
        ...item,
        hidden: !shownLabelIds.has(item.id), // 不在展示标签中的为隐藏状态
      }));
    }
  } catch (error) {
    console.error("获取标签列表失败:", error);
    uni.showToast({
      title: "加载失败，请稍后重试",
      icon: "error",
    });
  } finally {
    uni.hideLoading();
  }
};

// 页面加载
onMounted(() => {
  loadLabels();
});
</script>

<style scoped>
.content {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.page-body {
  flex: 1;
  padding: 20rpx;
}

.header-icon {
  width: 70rpx;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-svg {
  width: 44rpx;
  height: 44rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

.label-list {
  background-color: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
}

.label-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx 24rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.label-item:last-child {
  border-bottom: none;
}

.label-info {
  flex: 1;
  display: flex;
  align-items: center;
}

.label-name {
  font-size: 32rpx;
  color: #333333;
  margin-right: 20rpx;
}

.label-status {
  font-size: 24rpx;
  color: #999999;
  padding: 4rpx 12rpx;
  background-color: #f5f5f5;
  border-radius: 12rpx;
}

.label-actions {
  display: flex;
  align-items: center;
}

.action-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 16rpx;
  border-radius: 30rpx;
}

.action-btn.edit {
  background-color: #e3f2fd;
}

.action-btn.toggle {
  background-color: #e3f2fd;
}

.action-btn.delete {
  background-color: #ffebee;
}

.action-icon {
  width: 32rpx;
  height: 32rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 60rpx;
  text-align: center;
}

.empty-icon {
  width: 120rpx;
  height: 120rpx;
  opacity: 0.3;
  margin-bottom: 30rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #666666;
  margin-bottom: 16rpx;
}

.empty-tip {
  font-size: 28rpx;
  color: #999999;
}

/* 弹窗样式 */
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.dialog-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  overflow: hidden;
}

.dialog-header {
  padding: 40rpx 40rpx 20rpx;
  text-align: center;
}

.dialog-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333333;
}

.dialog-body {
  padding: 20rpx 40rpx 40rpx;
}

.label-input {
  width: 100%;
  height: 80rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 12rpx;
  font-size: 30rpx;
  box-sizing: border-box;
}

.label-input:focus {
  border-color: #4361ee;
}

.dialog-footer {
  display: flex;
  border-top: 1rpx solid #f0f0f0;
}

.dialog-btn {
  flex: 1;
  height: 90rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  border: none;
  background-color: #ffffff;
}

.dialog-btn.cancel {
  color: #666666;
  border-right: 1rpx solid #f0f0f0;
}

.dialog-btn.confirm {
  color: #4361ee;
  font-weight: 600;
}
</style>
